package com.stox.services.charting.manager;

import java.util.List;

import com.stox.services.charting.repository.ChartGroupFileRepository;
import com.stox.services.charting.repository.SavedChartFileRepository;
import com.stox.shared.charting.model.ChartGroup;
import com.stox.shared.charting.model.SavedChart;

public class ChartingManager {
	
	public static final ChartingManager INSTANCE = new ChartingManager();
	
	private ChartingManager() {
		
	}

	public void save(SavedChart chart) {
		SavedChartFileRepository.INSTANCE.saveOrUpdate(chart);
		ChartGroup chartGroup = ChartGroupFileRepository.INSTANCE.findOne(chart.getChartGroupId());
		chartGroup.getCharts().add(chart);
		ChartGroupFileRepository.INSTANCE.saveOrUpdate(chartGroup);
	}

	public void save(ChartGroup chartGroup) {
		ChartGroupFileRepository.INSTANCE.saveOrUpdate(chartGroup);
		//When a chart group is created, there are no charts in it.
		//Thus no need to handle that
	}
	
	public void deleteChartGroup(Long chartGroupId) {
		ChartGroupFileRepository.INSTANCE.delete(chartGroupId);
		List<SavedChart> charts = SavedChartFileRepository.INSTANCE.findByChartGroupId(chartGroupId);
		for(SavedChart chart : charts){
			SavedChartFileRepository.INSTANCE.delete(chart.getId());
		}
	}
	
	public void deleteSavedChart(Long savedChartId) {
		SavedChartFileRepository.INSTANCE.delete(savedChartId);
	}


	public List<ChartGroup> findAll() {
		return ChartGroupFileRepository.INSTANCE.findAll();
	}

	public List<SavedChart> findByChartGroupId(Long id) {
		return SavedChartFileRepository.INSTANCE.findByChartGroupId(id);
	}

	public String loadContent(Long chartGroupId, Long savedChartId) {
		return SavedChartFileRepository.INSTANCE.load(chartGroupId, savedChartId);
	}
	
}
